package video.com.text;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huamai.poc.IPocEngineEventHandler;
import com.huamai.poc.PocEngine;
import com.huamai.poc.PocEngineFactory;


/**
 * TODO
 * 1.http与sip登陆分开
 * 2.
 */
public class MainActivity extends Activity {

    private static final String TAG = "pocSDK_MainActivity";
    private TextView mServerTipTv, mSessionTip2Tv;
    private EditText mInputEt;
    private Button mAudioButton, mVideoButton;
    private Button mLoginBt, mLoginOutBt;
    private View mInputPanel, mCallingPanel, mLoginPanel;
    private AlertDialog mOutCallDialog, mInCallDialog;

    private PocEngine mPocEngine;
    private final IPocEngineEventHandler mPocEventHandler = new IPocEngineEventHandler() {

        @Override
        public void onServiceConnected() {
            mServerTipTv.setText("服务已登陆: " + ((EditText) findViewById(R.id.login_uid)).getText());
            mInputPanel.setVisibility(View.VISIBLE);
            mLoginPanel.setVisibility(View.GONE);
        }

        @Override
        public void onServiceDisconnected(int reason) {
            mServerTipTv.setText("服务已断开，错误码：" + reason);
            mInputPanel.setVisibility(View.GONE);
            mLoginPanel.setVisibility(View.VISIBLE);
        }

        @Override
        public void onIncoming(long sessionId, int type, long callerUid, String extra) {
            Log.d("pocSDK", "onIncoming " + sessionId + " extra=" + extra);
            mOutCallDialog.dismiss();
            mInCallDialog.setTitle("来电: " + callerUid);
            mInCallDialog.show();
        }

        @Override
        public void onIgnoreIncoming(int type, long callerUid) {
            //当前已有会话，新的来电被自动拒绝
            showToast("来电被拒绝: " + callerUid);
        }

        @Override
        public void onRemoteRinging(long sessionId, long uid) {
            mOutCallDialog.setTitle("远端正在响铃: " + uid);
        }

        @Override
        public void onSessionConnected(long sessionId, long uid, int sessionType) {
            mSessionTip2Tv.setText("已建立会话: 远端" + uid);
            mOutCallDialog.dismiss();
            mInputPanel.setVisibility(View.GONE);
            mLoginPanel.setVisibility(View.GONE);
            mCallingPanel.setVisibility(View.VISIBLE);

            updateCallingPanel(sessionType == SessionType.TYPE_VIDEO);
            if (sessionType == SessionType.TYPE_VIDEO) {
                setupLocalVideo();
                setupRemoteVideo(uid);
            }
        }

        @Override
        public void onSessionDisconnected(long sessionId, int reason) {
            mSessionTip2Tv.setText("已断开会话");
            mOutCallDialog.dismiss();
            mInputPanel.setVisibility(View.VISIBLE);
            mLoginPanel.setVisibility(View.VISIBLE);
            mCallingPanel.setVisibility(View.GONE);
            removeSurface();

            if (reason == SessionReason.TERMINATED) {
                showToast("挂断");
            } else if (reason == SessionReason.REMOTE_BUSY) {
                showToast("对方繁忙");
            } else if (reason == SessionReason.REMOTE_OFFLINE) {
                showToast("对方离线");
            } else {
                showToast("未定义");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_video_chat_view);

        setupViewListener();
        initializePocEngine();
    }

    private void setupViewListener() {
        mServerTipTv = (TextView) findViewById(R.id.tip);
        mSessionTip2Tv = (TextView) findViewById(R.id.tip2);
        mInputEt = (EditText) findViewById(R.id.input_et);
        mAudioButton = (Button) findViewById(R.id.audio_call);
        mVideoButton = (Button) findViewById(R.id.video_call);
        mLoginBt = (Button) findViewById(R.id.login);
        mLoginOutBt = (Button) findViewById(R.id.loginout);
        mLoginPanel = findViewById(R.id.login_panel);
        mInputPanel = findViewById(R.id.input_panel);
        mCallingPanel = findViewById(R.id.video_call_menu_panel);
        mOutCallDialog = new AlertDialog.Builder(this)
                .setNegativeButton("挂断", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tryHangUp();
                    }
                }).setCancelable(false).create();
        mInCallDialog = new AlertDialog.Builder(this)
                .setNegativeButton("接听", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        tryAcceptCall();
                    }
                }).setPositiveButton("挂断", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tryHangUp();
                    }
                }).setCancelable(false).create();


        //登陆
        mLoginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginService();
            }
        });
        //登出
        mLoginOutBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginoutService();
            }
        });

        //发起语音
        mAudioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeCall(mInputEt.getText().toString(), false);
            }
        });
        //发起视频
        mVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeCall(mInputEt.getText().toString(), true);
            }
        });
        //免提
        findViewById(R.id.btn_hangfree).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPocEngine.setEnableSpeakerphone(true, mPocEngine.getCurrentSessionId());
            }
        });
        //静音
        findViewById(R.id.video_call_mute_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPocEngine.muteMic();
            }
        });
        //仅语音(关闭画面推送)
        findViewById(R.id.btn_voice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("pocSDK", "pauseVideo=" + !mPocEngine.isVideoOnPause());
                mPocEngine.pauseVideo(!mPocEngine.isVideoOnPause());
            }
        });
        //切换摄像头
        findViewById(R.id.btn_switch_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPocEngine.switchCamera();
            }
        });
        //挂断
        findViewById(R.id.btn_end_call).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tryHangUp();
            }
        });
    }

    private void initializePocEngine() {
        mPocEngine = PocEngineFactory.get();
        mPocEngine.addEventHandler(mPocEventHandler);
    }

    private void loginService() {
//        if (!mPocEngine.hasLogin()) {
            mServerTipTv.setText("loginService...");
            long uid = 0;
            try {
                uid = Long.valueOf(((EditText) findViewById(R.id.login_uid)).getText().toString());
            } catch (Exception e) {
            }
            if (uid > 0) {
                mPocEngine.login(uid, 13579);
            }
//        } else {
//            Toast.makeText(this, "已登陆", Toast.LENGTH_SHORT).show();
//        }
    }

    private void loginoutService() {
        mPocEngine.logout();
    }

    // Step 3
    private void setupLocalVideo() {
        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        if (container.getChildCount() > 0) {
            container.removeAllViews();
        }
        View surfaceView = mPocEngine.getRendererView(IPocEngineEventHandler.SurfaceType.LOCAL);
        if (surfaceView != null) {
            ((SurfaceView) surfaceView).setZOrderMediaOverlay(true);
            container.addView(surfaceView);
            mPocEngine.sendLocalVideo(mPocEngine.getCurrentSessionId());
        } else {
            showToast("get local surface view null");
        }
    }

    // Step 5
    private void setupRemoteVideo(long uid) {
        FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container);
        if (container.getChildCount() > 0) {
            container.removeAllViews();
        }
        View surfaceView = mPocEngine.getRendererView(IPocEngineEventHandler.SurfaceType.REMOTE);
        if (surfaceView != null) {
            container.addView(surfaceView);
            surfaceView.setTag(uid);
        } else {
            showToast("get remote surface view null");
        }
    }


    private void makeCall(String input, boolean isVideoCall) {
        if (TextUtils.isEmpty(input)) {
            Toast.makeText(this, "请输入呼叫id", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mPocEngine.hasServiceConnected()) {
            Toast.makeText(this, "服务连接已断开", Toast.LENGTH_SHORT).show();
            return;
        }
        long uid = Long.valueOf(input);
        if (isVideoCall) {
            mPocEngine.makeVideoCall(uid, "");
        } else {
            mPocEngine.makeAudioCall(uid, "");
        }

        mOutCallDialog.setTitle("连接中");
        mOutCallDialog.show();
        mInCallDialog.dismiss();
    }

    private void tryAcceptCall() {
        boolean ret = mPocEngine.acceptCall(mPocEngine.getCurrentSessionId());
        if (!ret) {
            showToast("接听失败 " + mPocEngine.getCurrentSessionId());
        }
    }

    private void tryHangUp() {
        mPocEngine.hangUpCall(mPocEngine.getCurrentSessionId());
    }

    private void removeSurface() {
        ((ViewGroup) findViewById(R.id.local_video_view_container)).removeAllViews();
        ((ViewGroup) findViewById(R.id.remote_video_view_container)).removeAllViews();
    }

    private void updateCallingPanel(boolean isVideoCall) {
        ((ViewGroup) findViewById(R.id.video_call_mute_btn).getParent()).setVisibility(isVideoCall ? View.VISIBLE : View.GONE);
        ((ViewGroup) findViewById(R.id.btn_voice).getParent()).setVisibility(isVideoCall ? View.VISIBLE : View.GONE);
        ((ViewGroup) findViewById(R.id.btn_switch_camera).getParent()).setVisibility(isVideoCall ? View.VISIBLE : View.GONE);
    }

    private void showToast(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }
}